/// <reference path="../../Pages/indexnew.html" />
/// <reference path="../../Pages/indexnew.html" />
// ** Step 4: Create SPAppContext service:  **//
(function () {
    'use strict';

    var serviceId = 'spappcontext';
    var app = angular.module('app');
    app.service(serviceId, ['common','$window','$location', spappcontext]);
   
   
    function spappcontext(common, $window, $location) {

        var getLogFn = common.logger.getLogFn;
        var log = getLogFn(serviceId);
        var service = this;
        var spweb = {
            providerUrl: '',
            SPAppWebUrl: '',
            SPHostUrl: ''
        };
       
        service.hostWeb = spweb;
        init();

        function init() {
            var test = jQuery.getQueryStringValue('SPHostUrl');
            if(decodeURIComponent(jQuery.getQueryStringValue('SPHostUrl')) === "undefined" )
            {
                loadSPAppContext();
            }
            else
            {

                createSPAppContext();
            }
        }

        function loadSPAppContext() {

            log('loading spcontext cookie');
            service.hostWeb.providerUrl = $.cookie("ProviderUrl");
            service.hostWeb.SPAppWebUrl = $.cookie("SPAppWebUrl");
            service.hostWeb.SPHostUrl = $.cookie("SPHostUrl");
        }

        function createSPAppContext() {
            log('writing spcontext cookie');
            var ProviderUrl = $window.location.protocol + "//" + $window.location.host;
            $.cookie("ProviderUrl", ProviderUrl, { path: '/' });

             var appWebUrl = decodeURIComponent(jQuery.getQueryStringValue('SPAppWebUrl'));
            $.cookie("SPAppWebUrl", appWebUrl, { path: '/' });
         
            var url = decodeURIComponent(jQuery.getQueryStringValue('SPHostUrl'));       
            $.cookie('SPHostUrl', url, { path: '/' });

            //var title = decodeURIComponent(jQuery.getQueryStringValue('SPHostTitle'));
            //$.cookie('SPHostTitle', title, { path: '/' });

            //var logoUrl = decodeURIComponent(jQuery.getQueryStringValue('SPHostLogoUrl'));
            //$.cookie('SPHostLogoUrl', logoUrl, { path: '/' });

            $window.location.href = ProviderUrl + "/index.html";

        }

       
    }
})();